package cn.leshua.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.thoughtworks.xstream.XStream;

import cn.leshua.res.LeshuaMicroPayRes;

/**
 * @author eden
 * @date 2018/5/21 下午3:36
 * @desc
 */
public class LeshuaUtils {

    //打log用
    private static Logger logger = LoggerFactory.getLogger(LeshuaUtils.class);
    
	public static byte[] readInput(InputStream in) throws IOException {
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		int len = 0;
		byte[] buffer = new byte[1024];
		try {
			while ((len = in.read(buffer)) > 0) {
				out.write(buffer, 0, len);
			}
		} finally {
			out.close();
			in.close();
		}
		return out.toByteArray();
	}

    public static String inputStreamToString(InputStream is) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int i;
        while ((i = is.read()) != -1) {
            baos.write(i);
        }
        return baos.toString("UTF-8");
    }


    public static InputStream getStringStream(String sInputString) throws UnsupportedEncodingException {
        ByteArrayInputStream tInputStringStream = null;
        if (sInputString != null && !sInputString.trim().equals("")) {
            tInputStringStream = new ByteArrayInputStream(sInputString.getBytes("UTF-8"));
        }
        return tInputStringStream;
    }

    public static Object getObjectFromXML(String xml, Class<?> tClass) {
       return getObjectFromXML(xml, tClass, "xml");
    }
    
    public static Object getObjectFromXML(String xml, Class<?> tClass, String alias) {
        //将从API返回的XML数据映射到Java对象
        XStream xStreamForResponseData = new XStream();
        XStream.setupDefaultSecurity(xStreamForResponseData);  
        xStreamForResponseData.alias(alias, tClass);
        xStreamForResponseData.allowTypes(new Class[]{tClass});
        xStreamForResponseData.ignoreUnknownElements();//暂时忽略掉一些新增的字段
        return xStreamForResponseData.fromXML(xml);
    }
    
    /**
     * 将对象转换成map，key为属性名，value为属性值，值为null的属性排除
     * @param obj
     * @return
     */
	public static Map<String, String> toMap(Object obj) {
		Map<String, String> map = new HashMap<String,String>();
		Field[] fields = obj.getClass().getFields();
		for (Field field : fields) {
			try {
				Object val = field.get(obj);
				if (val != null) {
					map.put(field.getName(), String.valueOf(val));
				}
			} catch (IllegalArgumentException e) {
				logger.error(e.getMessage(), e);
			} catch (IllegalAccessException e) {
				logger.error(e.getMessage(), e);
			}
		}
		return map;
	}
	
	/**
	 * 计算失效时间
	 * @param now
	 * @param expireInMinutes
	 * @param dateFormat
	 * @return
	 */
	public static String calcExpireTime(Date now, String expireInMinutes, SimpleDateFormat dateFormat) {
		return dateFormat.format(now.getTime() + Long.parseLong(expireInMinutes) * 60 * 1000);
	}

}

